<template>
  <div class="app-container">

    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      
      <el-card>
          <div slot="header">
            <span><i class="el-icon-s-tools"></i> 基本信息</span>
            <span style="margin-left: 50px; font-weight: bold;">
              <el-button
                type="warning"
                plain
                icon="el-icon-warning"
                size="mini"
                @click="handleInfo"
              >提示</el-button>
            </span>
          </div>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="nodeName">
                <span slot="label">
                  节点名称
                  <el-tooltip placement="right" effect="light">
                    <div slot="content">集群各节点名称要求唯一<br></div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-input v-model="form.nodeName" :maxlength="20" placeholder="请输入节点名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="mode">
                <span slot="label">集群模式</span>
                <!-- @change="changeMode" -->
                <el-select v-model="form.mode" placeholder="请选择集群模式" @change="changeMode">
                  <el-option
                    v-for="dict in dict.type.cluster_mode"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="deviceType">
                <span slot="label">设备类型</span>
                <el-select v-model="form.deviceType" placeholder="请选择设备类型" v-if="form.mode=='MB'">
                  <el-option
                    v-for="dict in dict.type.device_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
                <el-select v-model="form.deviceType" placeholder="请选择设备类型" v-if="form.mode=='MM'">
                  <el-option
                    v-for="dict in dict.type.device_type2"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="vrrpProto">
                <span slot="label">
                  集群间通信协议
                  <el-tooltip placement="right" effect="light">
                    <div slot="content">根据集群节点间网络环境选择，要求VRRP协议通信正常：<br>1.在同一网段时，建议选择组播，<br>2.在不同网段时，建议选择单播，<br>3.其它复杂环境，选择VRRP协议通信正常方式即可</div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-select v-model="form.vrrpProto" placeholder="请选择协议">
                  <el-option
                    v-for="dict in dict.type.vrrp_proto"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="deviceIp">
                <span slot="label">本机设备IP地址</span>
                <el-input v-model="form.deviceIp" :maxlength="15" placeholder="请输入本机设备IP地址" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="peerIp" :rules="rules.peerIp" v-if="form.vrrpProto == 'multicast'">
                <span slot="label">对端设备IP地址</span>
                <el-input v-model="form.peerIp" :maxlength="15" placeholder="请输入对端设备IP地址" />
              </el-form-item>
              <el-form-item prop="peerIp" :rules="rules.peerIp2" v-if="form.vrrpProto == 'unicast'">
                <span slot="label">对端设备IP地址</span>
                <el-input v-model="form.peerIp" :maxlength="15" placeholder="请输入对端设备IP地址" />
              </el-form-item>
            </el-col>
          </el-row>
      </el-card>
      <el-row>
        <el-card>
            <div slot="header">
              <span><i class="el-icon-s-tools"></i> 虚拟路由（主）</span>
              <span style="margin-left: 100px; font-weight: bold;">运行状态：</span>
              <span>
                <el-tag size="small" type="success" v-if="this.form.status=='MASTER'">{{ getStatus(this.form.status) }}</el-tag>
                <el-tag size="small" type="info" v-if="this.form.status=='BACKUP'">{{ getStatus(this.form.status) }}</el-tag>
                <el-tag size="small" type="warning" v-if="this.form.status=='UNKNOWN'">{{ getStatus(this.form.status) }}</el-tag>
                <el-tag size="small" type="danger" v-if="this.form.status=='DOWN'">{{ getStatus(this.form.status) }}</el-tag>
              </span>
            </div>
            <el-col :span="12">
              <el-form-item prop="virrouterId">
                <span slot="label">
                  虚拟路由ID
                  <el-tooltip placement="right" effect="light">
                    <div slot="content" v-if="this.form.mode=='MB'">默认配置50，谨慎修改，<br>1.要求集群各节点相同<br></div>
                    <div slot="content" v-if="this.form.mode=='MM'">默认配置50，谨慎修改，<br>1.要求集群各节点相同，<br>2.与虚拟路由（备）不相同</div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-input v-model.number="form.virrouterId" :maxlength="3" placeholder="请输入虚拟路由ID" >
                  <!-- <el-button slot="append" icon="el-icon-edit"></el-button> -->
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="priority">
                <span slot="label">
                  优先级
                  <el-tooltip placement="right" effect="light">
                    <div slot="content" v-if="this.form.mode=='MB' && this.form.deviceType=='master'">
                      默认配置100，谨慎修改<br>要求主设备（如100）高于从设备（如90）</div>
                    <div slot="content" v-if="this.form.mode=='MB' && this.form.deviceType=='backup'">
                      默认配置90，谨慎修改<br>要求从设备（如90）低于主设备（如100）</div>
                    <div slot="content" v-if="this.form.mode=='MM' && this.form.deviceType=='masterA'">
                      默认配置100，谨慎修改<br>要求MASTER-A设备（如100）高于MASTER-B设备（如90）</div>
                    <div slot="content" v-if="this.form.mode=='MM' && this.form.deviceType=='masterB'">
                      默认配置90，谨慎修改<br>要求MASTER-B设备（如90）低于MASTER-A设备（如100）</div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-input v-model.number="form.priority" :maxlength="3" placeholder="请输入优先级">
                  <!-- <el-button slot="append" icon="el-icon-edit"></el-button> -->
                </el-input>
              </el-form-item>
            </el-col>
        
        </el-card>
      </el-row>
      <el-row v-if="form.mode == 'MM'">
        <el-card>
            <div slot="header"><span><i class="el-icon-s-tools"></i> 虚拟路由（备）</span>
              <span style="margin-left: 100px; font-weight: bold;">运行状态：</span>
              <span>
                <el-tag size="small" type="success" v-if="this.form.status2=='MASTER'">{{ getStatus(this.form.status2) }}</el-tag>
                <el-tag size="small" type="info" v-if="this.form.status2=='BACKUP'">{{ getStatus(this.form.status2) }}</el-tag>
                <el-tag size="small" type="warning" v-if="this.form.status2=='UNKNOWN'">{{ getStatus(this.form.status2) }}</el-tag>
                <el-tag size="small" type="danger" v-if="this.form.status2=='DOWN'">{{ getStatus(this.form.status2) }}</el-tag>
              </span>
            </div>
            <el-col :span="12">
              <el-form-item prop="virrouterId2">
                <span slot="label">
                  虚拟路由ID
                  <el-tooltip placement="right" effect="light">
                    <div slot="content">默认配置51，谨慎修改，<br>1.要求集群各节点相同，<br>2.与虚拟路由（主）不相同</div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-input v-model.number="form.virrouterId2" :maxlength="3" placeholder="请输入虚拟路由ID" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item prop="priority2">
                <span slot="label">
                  优先级
                  <el-tooltip placement="right" effect="light">
                    <div slot="content" v-if="this.form.deviceType=='masterA'">
                      默认配置90，谨慎修改<br>要求MASTER-A设备（如90）低于MASTER-B设备（如100）</div>
                    <div slot="content" v-if="this.form.deviceType=='masterB'">
                      默认配置100，谨慎修改<br>要求MASTER-B设备（如100）高于MASTER-A设备（如90）</div>
                    <i class="el-icon-question"></i>
                  </el-tooltip>
                </span>
                <el-input v-model.number="form.priority2" :maxlength="3" placeholder="请输入优先级" />
              </el-form-item>
            </el-col>
        </el-card>
      </el-row>
    </el-form>
 
    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-100px;margin-top:10px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="getCluster()">返回</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import { getCluster, updateCluster } from "@/api/lbsysconfig/cluster";
import { isIPv4 } from "@/api/snowfieldValidate";

export default {
  name: "Cluster",
  dicts: ['cluster_mode', 'device_type', 'device_type2', 'vrrp_proto'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      peerIpRequired: true,
      // 表单参数
      form: {
        id: 1,
        nodeName: '',
        mode: '',
        deviceType: '',
        deviceIp: '',
        peerIp: '',
        virrouterId: '50',
        priority: '',
        status:'',
        virrouterId2: '51',
        priority2: '',
        status2:''
      },
      // 表单校验
      rules: {
        nodeName: [
          { required: true, message: "节点名称不能为空", trigger: "blur" }
        ],
        mode: [
          { required: true, message: "集群模式不能为空", trigger: "change" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        vrrpProto: [
          { required: true, message: "协议不能为空", trigger: "change" }
        ],
        deviceIp: [
          { required: true, message: "本机设备IP地址不能为空", trigger: "blur" },
          { validator:(rule,value,callback)=>{
            if(!isIPv4(value)){
              callback(new Error("IP地址格式有误"));
              return;
            }

            callback();
          }, message: "IP地址格式有误", trigger: 'blur'},
        ],
        peerIp: [
          { required: false, message: "对端设备IP地址不能为空", trigger: "blur" },
          { validator:(rule,value,callback)=>{
            if(value != null && value != "" && !isIPv4(value)){
              callback(new Error("IP地址格式有误"));
              return;
            }

            callback();
          }, message: "IP地址格式有误", trigger: 'blur'},
        ],
        peerIp2: [
          { required: true, message: "对端设备IP地址不能为空", trigger: "blur" },
          { validator:(rule,value,callback)=>{
            if(value != "" && !isIPv4(value)){
              callback(new Error("IP地址格式有误"));
              return;
            }

            callback();
          }, message: "IP地址格式有误", trigger: 'blur'},
        ],
        virrouterId: [
          { required: true, message: "虚拟路由ID不能为空", trigger: "blur" },
          { type: 'integer', min: 1, max:255, message: '数据格式错误，范围[1,255]', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: "优先级不能为空", trigger: "blur" },
          { type: 'integer', min: 1, max:255, message: '数据格式错误，范围[1,255]', trigger: 'blur' }
        ],
        virrouterId2: [
          { required: true, message: "虚拟路由ID不能为空", trigger: "blur" },
          { type: 'integer', min: 1, max:255, message: '数据格式错误，范围[1,255]', trigger: 'blur' },
          { validator:(rule,value,callback)=>{
            if(this.form.virrouterId == value){
              callback(new Error("主备虚拟路由ID不能相同"));
              return;
            }

            callback();
          }, trigger: 'blur'},
        ],
        priority2: [
          { required: true, message: "优先级不能为空", trigger: "blur" },
          { type: 'integer', min: 1, max:255, message: '数据格式错误，范围[1,255]', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    this.getCluster();
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        id: null,
        nodeName: null,
        mode: null,
        deviceType: null,
        vrrpProto: null,
        deviceIp: null,
        peerIp: null,
        virrouterId: null,
        priority: null,
        virrouterId2: null,
        priority2: null
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    getCluster() {
      this.reset();
      const id = 1;
      getCluster(id).then(response => {
        this.form = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCluster(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getCluster();
            });
          } else {
            addCluster(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getCluster();
            });
          }
        }
      });
    },
    changeMode(){
      if(this.form.mode == "MM"){
        //双主
        this.form.deviceType = "masterA";
      } else if(this.form.mode == "MB"){
        //主从
        this.form.deviceType = "master";
      }
    },
    getStatus(status){
      if(status == "MASTER"){
        //启用
        return "启用";
      } else if(status == "BACKUP"){
        //备用
        return "备用";
      } else if(status == "DOWN"){
        //停用
        return "停用";
      } else {
        //未知
        return "未知";
      }
    },
    handleInfo(){
      const h = this.$createElement;
      this.$msgbox({
          title: '提示',
          message: h('p', {style : 'color:red; font-size:small; font-weight:bold'}, [
            h('li', null, '1.配置信息保存后不会立即生效，在前端代理执行 [状态更新] 操作或 [重载] 操作后才生效'),
            //h('li', null, '2.'),
          ]),
          showCancelButton: false,
          confirmButtonText: '关闭',
          cancelButtonText: '取消',
        }).then(action => {
          
        }).catch(() => {
          
        });
    },
  }
};
</script>
